package com.graduation.lastproject.util.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description:全局shiro拦截分发realm
 */
public class LoginsModularRealmAuthenticator extends ModularRealmAuthenticator {
    private static Logger logger=LoggerFactory.getLogger(LoginsModularRealmAuthenticator.class);
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken){
        logger.info("分发realm:----------------------------");
        //判断getRealm()是够返回为空
        super.assertRealmsConfigured();
        //强制转换回自定义的loginsToken
        LoginsToken loginsToken=(LoginsToken) authenticationToken;
        //登录类型
        String loginType=loginsToken.getLoginType();
        //所有Realm
        Collection<Realm> realms=getRealms();
        //登录类型获取对应的
        Collection<Realm> typeRealms = new ArrayList<>();
        for (Realm realm : realms) {
            if (realm.getName().contains(loginType))
                typeRealms.add(realm);
        }
        logger.info("对用的reaml:-------------:"+typeRealms.toString());
        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1){
            logger.info("doSingleRealmAuthentication() execute "+typeRealms.iterator().next());
           /* AuthenticationInfo authenticationInfo = doSingleRealmAuthentication(new BusinessRealm(), loginsToken);*/
            return doSingleRealmAuthentication(typeRealms.iterator().next(),loginsToken);
        }
        else
            return doMultiRealmAuthentication(typeRealms,loginsToken);
    }
}
